package com.basic.common.utils;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Date;
import java.util.List;
import java.util.Map;

public class ExportExcel {
    /**
     * @param sheetName 工作表的名字
     * @param column  列名
     * @param data  需要导出的数据    ( map的键定义为列的名字 一定要和column中的列明保持一致  )
     * @param response
     */
    public static void exportExcel(String sheetName, List<String> column, List<Map<String,Object>> data, HttpServletRequest request, HttpServletResponse response){
        Workbook workbook = new XSSFWorkbook(); // 使用XSSFWorkbook处理XLSX格式

        // 创建sheet
        Sheet sheet = workbook.createSheet(sheetName);
        // 表头行
        Row headRow = sheet.createRow(0);
        for (int i = 0; i < column.size(); i++) {
            headRow.createCell(i).setCellValue(column.get(i));
        }

        // 数据行
        for (int i = 0; i < data.size(); i++) {
            Row dataRow = sheet.createRow(sheet.getLastRowNum() + 1);
            for (int x = 0; x < column.size(); x++) {
                Object cellValue = data.get(i).get(column.get(x));
                if (cellValue instanceof Date) {
                    // 如果是日期类型，使用适当的日期格式进行格式化
                    Cell cell = dataRow.createCell(x);
                    CellStyle cellStyle = workbook.createCellStyle();
                    CreationHelper createHelper = workbook.getCreationHelper();
                    cellStyle.setDataFormat(createHelper.createDataFormat().getFormat("yyyy-MM-dd HH:mm:ss"));
                    cell.setCellValue((Date) cellValue);
                    cell.setCellStyle(cellStyle);
                } else {
                    // 否则按照原来的逻辑处理
                    dataRow.createCell(x).setCellValue(cellValue == null ? "" : cellValue.toString());
                }
            }
        }

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); // 设置XLSX的内容类型
        try {
            // 获取浏览器名称
            String agent = request.getHeader("user-agent");
            String filename = sheetName + ".xlsx";
            // 不同浏览器需要对文件名做特殊处理
            if (agent.contains("Firefox")) {
                // 火狐浏览器
//                filename = "=?UTF-8?B?" + new BASE64Encoder().encode(filename.getBytes("utf-8")) + "?=";
                String encodedFilename = Base64.getEncoder().encodeToString(filename.getBytes(StandardCharsets.UTF_8));
                filename = "=?UTF-8?B?" + encodedFilename + "?=";
                filename = filename.replaceAll("\r\n", "");
            } else {
                // IE及其他浏览器
                filename = URLEncoder.encode(filename, "utf-8");
                filename = filename.replace("+", " ");
            }
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
            // 推送到浏览器
            response.setHeader("Content-Disposition", "attachment;filename=" + filename);
            workbook.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void exportExcelWithoutData(String sheetName,  HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); // 设置XLSX的内容类型
        try {
            // 获取浏览器名称
            String agent = request.getHeader("user-agent");
            String filename = sheetName + ".xlsx";
            // 不同浏览器需要对文件名做特殊处理
            if (agent.contains("Firefox")) {
                // 火狐浏览器
                String encodedFilename = Base64.getEncoder().encodeToString(filename.getBytes(StandardCharsets.UTF_8));
                filename = "=?UTF-8?B?" + encodedFilename + "?=";
                filename = filename.replaceAll("\r\n", "");
            } else {
                // IE及其他浏览器
                filename = URLEncoder.encode(filename, "utf-8");
                filename = filename.replace("+", " ");
            }
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
            // 推送到浏览器
            response.setHeader("Content-Disposition", "attachment;filename=" + filename);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
